package com.zhouyu.exampleThread.lockTest;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:交替打印
 */
public class DThread {
  volatile private static DThread dThread;
  volatile private static int nextPrintWho = 1;
  private static ReentrantLock lock = new ReentrantLock();
  Condition condition1 = lock.newCondition();
  Condition condition2 = lock.newCondition();
  Condition condition3 = lock.newCondition();

  public DThread getSingleTon(){
    if(dThread==null){
        synchronized (DThread.class){
          if(dThread==null){
            dThread=new DThread();
          }
        }
    }
    return dThread;
  }

  public void runAll() {
    new Thread(() -> {
      try {
        lock.lock();
        while (nextPrintWho!=1){
          condition1.await();
        }
        System.out.println("我是线程一");
        nextPrintWho=2;
        //达到什么条件就开启阻塞或者放弃阻塞
        condition2.signal();
        System.out.println("条件2开启");
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally {
        lock.unlock();
      }
    }).start();
    new Thread(() -> {
      try {
        lock.lock();
        while (nextPrintWho!=2){
          condition2.await();
        }
        System.out.println("我是线程二");
        nextPrintWho=3;
        condition3.signal();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally {
        lock.unlock();
      }
    }).start();
    new Thread(() -> {
      try {
        lock.lock();
        while (nextPrintWho!=3){
          condition3.await();
        }
        System.out.println("我是线程三");
        nextPrintWho=1;
        condition1.signal();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally {
        lock.unlock();
      }
    }).start();
  }
}
